import { WECHAT, HTML5 } from 'cc/env';
import { bannerwxwx } from './bannerwxwx';

// 3 X 5 矩阵广告
export class MatrixCustomMultiAd {
  private static instance = null as unknown as MatrixCustomMultiAd;
  private customAd = null;
  private hasShow = false;
  public static Instance() {
    if (!MatrixCustomMultiAd.instance) {
      MatrixCustomMultiAd.instance = new MatrixCustomMultiAd();
    }
    return MatrixCustomMultiAd.instance;
  }
  constructor() { }
  public create() {
    const that = this;
    // 创建之前，先销毁旧广告
    this.destroy();
    this.hasShow = false;
    if (WECHAT) {
      const { screenWidth, screenHeight } = wx.getSystemInfoSync();
      this.customAd = wx.createCustomAd({
        adUnitId: bannerwxwx.wxmarmulitfgad,
        style: { left: 0.5 * screenWidth - 150, top: 0.75 * screenHeight, width: 300 }
      })
      this.customAd.onLoad(() => {
        if (that.hasShow) that.show();
      });
      this.customAd.onError((err: any) => {
        console.log('matrix custom ad error ', err);
      })      
    }
  }

  public show() {
    if (!this.customAd) {
      return;
    }
    this.hasShow = true;
    if (WECHAT) {
      this.customAd.show().catch((err: any) => {
        console.log('matrix custom ad show error ', err);
      })
    }
  }
  // 用户自己手动关闭
  public hide() {
    if (!this.customAd) {
      return;
    }
    this.hasShow = false;
    if (WECHAT) {
      this.customAd.hide();
    }
  }
  public destroy() {
    if (WECHAT) {
      if (this.customAd) {
        this.customAd.destroy();
        this.customAd = null;
      }
    }
  }
}